package com.android.lyricshow.ui;

import java.util.ArrayList;
import java.util.HashMap;

import com.android.lyricshow.R;
import com.android.lyricshow.bean.SongBean;
import com.android.lyricshow.data.DataProvider;
import com.android.lyricshow.service.IService;
import com.android.lyricshow.service.PlayService;
import com.android.lyricshow.until.AppUntil;
import com.android.lyricshow.until.KEY;
import com.android.lyricshow.until.LogPrint;
import com.android.lyricshow.until.OP;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;

public class LyricShowMain extends Activity implements TabHost.OnTabChangeListener, View.OnClickListener {
	
	private ImageView mPlayStatus = null;
	
	private TextView mPlayTitle	= null;
	
	private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, TabInfo>();
    
    private TabHost mTabHost	= null;
    
    private TabInfo mLastTab	= null;
    
    private DataProvider mData	= null;
    
    private ServiceReceiver mReceiver = null;
    
    private IService mService	= null;
	
    private boolean mIsPlay		= false;
    @Override
 	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		initializeView();
		initializeData();
		initializeTabHost(savedInstanceState);
	}
	
    private void initializeView(){
    	
    	mPlayStatus	= (ImageView)findViewById(R.id.main_play_status);
    	mPlayTitle	= (TextView)findViewById(R.id.main_play_title);
    	
		mPlayStatus.setOnClickListener(this);
		mPlayTitle.setOnClickListener(this);
    }
    
    private void initializeData(){
    	
    	mReceiver = new ServiceReceiver();
    	registerReceiver(mReceiver, new IntentFilter(KEY.PLAY_RECEIVER));
    	
    	Intent it = new Intent(this, PlayService.class);
    	
    	it.putExtra(KEY.NOW_PLAYING, 0);
    	
    	startService(it);
		bindService(it, mConnection, 0);
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	
    	LogPrint.d("LyricShowMain Destroy");
    	
    	if(mReceiver != null){
    		unregisterReceiver(mReceiver);
    		mReceiver = null;
    	}
    	
    	if(mConnection != null){
    		unbindService(mConnection);
    		mConnection = null;
    	}
    }
    
	public void initializeTabHost(Bundle args){
		
		mData = new DataProvider(this);
		
		Bundle bd = new Bundle();
		
		bd.putSerializable(KEY.SONG_BEAN_LIST, mData.getSongList());
		bd.putSerializable(KEY.ALBUM_BEAN_LIST, mData.getAlbumList());
		bd.putSerializable(KEY.ARTIST_BEAN_LIST, mData.getArtistList());
		
		mTabHost = (TabHost)findViewById(android.R.id.tabhost);
		mTabHost.setup();
		
		addFragment(ArtistFragment.class, R.layout.tab_artist, bd);
		addFragment(SongFragment.class, R.layout.tab_song, bd);
		addFragment(AlbumFragment.class, R.layout.tab_ablum, bd);
		addFragment(PlayListFragment.class, R.layout.tab_playlist, bd);
		
        mTabHost.setOnTabChangedListener(this);
        
        onTabChanged(ArtistFragment.class.getName());
	}
	
	public void addToPlayList(SongBean sbean){
		
		if(mService != null){
			mService.addToPlayList(sbean);
		}
	}
	
	public void addToPlayList(ArrayList<SongBean> list){
		if(mService != null){
			mService.addToPlayList(list);
		}
	}
	
	private void startAndUpdateViews(Bundle bd){
		LogPrint.d("startAndUpdateViews");
		
		if(bd != null){
			SongBean sbean	= (SongBean)bd.getSerializable(KEY.SONG_BEAN);
			
			mIsPlay	= bd.getBoolean(KEY.IS_PAUSE, false)? false : true; 
	
			int during	= (int)sbean.getTime();	
			int curpos	= bd.getInt(KEY.CUR_POS, 0);
			
			//mProgress.setMax(during);
			//mProgress.setProgress(curpos);
			
			mPlayTitle.setText(sbean.getTitle());
			
			//mSumTime.setText(AppUntil.toTime(during));
			//mPlayTime.setText(AppUntil.toTime(curpos));
			
		}else{
			mIsPlay = true;
		}
		
		if(mIsPlay){
			mPlayStatus.setImageResource(R.drawable.main_pause);
			//synchronized (mLock) {
			//	mLock.notify();
			//}
		}else{
			mPlayStatus.setImageResource(R.drawable.main_pause);
		}
	}
	
	private void addFragment(Class<?> clss, int resId, Bundle bd){
		
		View tab = LayoutInflater.from(this).inflate(resId, null);

		String tag	= clss.getName();		
		TabInfo tabInfo	= null;
		
		this.addTab(this.mTabHost, this.mTabHost.newTabSpec(tag).setIndicator(tab),
                (tabInfo = new TabInfo(tag, clss, bd)));
		
		this.mapTabInfo.put(tabInfo.tag, tabInfo);
	}

    private void addTab(TabHost tabHost,TabHost.TabSpec tabSpec, TabInfo tabInfo) {

        tabSpec.setContent(new TabFactory(this));
        String tag = tabSpec.getTag();
        
        tabInfo.fragment = getFragmentManager().findFragmentByTag(tag);
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
        	
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            
            ft.detach(tabInfo.fragment);
            ft.commit();
            
            getFragmentManager().executePendingTransactions();
        }
        
        tabHost.addTab(tabSpec);
    }
    
	@Override
	public void onTabChanged(String tabId) {

		TabInfo newTab = this.mapTabInfo.get(tabId);

		if (mLastTab != newTab) {
            FragmentTransaction ft = this.getFragmentManager().beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                    ft.detach(mLastTab.fragment);
                }
            }
            
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(this, newTab.clss.getName(), newTab.args);
                    ft.add(android.R.id.tabcontent, newTab.fragment, newTab.tag);
                } else {
                    ft.attach(newTab.fragment);
                } 
            }     

            mLastTab = newTab;
            ft.commit();
            
            this.getFragmentManager().executePendingTransactions();
        }
	}
	
    class TabInfo {
		
        private String 		tag;
        private Class<?> 	clss;
        private Bundle 		args;
        private Fragment 	fragment;

        TabInfo(String tag, Class<?> clazz, Bundle args) {
            this.tag	= tag;
            this.clss	= clazz;
            this.args 	= args;
        }
    }
	
	class TabFactory implements TabContentFactory {
		private final Context mContext;

	    public TabFactory(Context context) {
	        mContext = context;
	    }
	    
	    public View createTabContent(String tag) {
	    	
	        View v = new View(mContext);
	        v.setMinimumWidth(0);
	        v.setMinimumHeight(0);
	        return v;
	    }
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = (IService)service;
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {}
	};
	
	private class ServiceReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bd = intent.getExtras();
			if(bd == null){
				return;
			}
			
			if(!bd.containsKey(KEY.NOTIFY)){
				return;
			}
			
			int code = bd.getInt(KEY.NOTIFY);		
			switch(code){
				case OP.START:
				case OP.NEXT:
					//SongBean sb = (SongBean)bd.getSerializable(KEY.SONG_BEAN);
					//LogPrint.d("Main Start " + sb.getTitle());
					
					startAndUpdateViews(bd);
					break;
				case OP.NO_PLAYLIST:
					break;
			}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(keyCode == KeyEvent.KEYCODE_BACK){
			TabInfo ti = this.mapTabInfo.get(mTabHost.getCurrentTabTag());
			((BaseFragment)ti.fragment).onBackKey();
			return false;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		if(mService == null){
			return;
		}
		
		switch(v.getId()){
		case R.id.main_play_status:
			if(mIsPlay){
				mService.pause();
				mPlayStatus.setImageResource(R.drawable.main_play);
			}else{
				mService.resume();
				mPlayStatus.setImageResource(R.drawable.main_pause);
			}
			
			mIsPlay = !mIsPlay;
			break;
		}
		
	}
}
